<template>
  <a-card :bordered="false">
    <a-spin :spinning="confirmLoading">
      <j-form-container>
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <div style="width: 140px; line-height: 32px; font-weight: bold; color: #000">{{ $t('参数设置') }}</div>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('小程序AppID')"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                prop="appletAppId"
              >
                <a-input v-model="model.appletAppId" :placeholder="$t('请输入小程序AppID')"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('小程序AppSecret')"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                prop="appletAppSecret"
              >
                <a-input v-model="model.appletAppSecret" :placeholder="$t('请输入小程序AppSecret')"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-row>
                <a-col :span="16" :offset="6">
                  <a-button type="primary" :disabled="confirmLoading" @click="submitForm" v-has="'BisSysParameterController:edit'">{{ $t('保存') }}</a-button>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
          <div style="width: 140px; line-height: 32px; font-weight: bold; color: #000" v-if="info.sysType != 6">{{ $t('扫普通二维码进小程序') }}</div>
          <a-row style="margin-top: 1%" v-if="info.sysType != 6">
            <a-col :span="24">
              <a-form-model-item
                :label="$t('二维码参数')"
                :labelCol="labelCol1"
                :wrapperCol="wrapperCol1"
                prop="appletQrPath"
              >
                <a-input v-model="model.appletQrPath" style="width: 20%"></a-input>
                <a-button type="primary" @click="saveQrPath" v-has="'BisSysParameterController:edit'" style="margin-left: 30px;">{{ $t('保存') }}</a-button>
                <span style="margin-left: 10px; color: orange">{{
                  $t('（请勿更改此参数，如有疑问请联系系统提供商）')
                }}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row v-if="info.sysType != 6">
            <a-col :span="24">
              <a-form-model-item :label="$t('校验文件')" :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                <a-upload
                  name="file"
                  accept=".txt"
                  :showUploadList="false"
                  :action="importExcelUrl"
                  :multiple="false"
                  :headers="tokenHeader"
                  @change="upload"
                  :data="{ biz: bizPath }"
                >
                  <a-button type="primary" v-has="'BisSysParameterController:edit'">{{ $t('上传') }}</a-button>
                </a-upload>
                <span style="margin-left: 10px; color: orange">{{
                  $t('（用于上传小程序后台配置“扫描普通二维码进入小程序”时下载的校验文件）')
                }}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <div style="width: 140px; line-height: 32px; font-weight: bold; color: #000" v-if="info.sysType == 6">APP{{ $t('下载') }}</div>
          <a-row style="margin-top: 1%" v-if="info.sysType == 6">
              <a-col :span="12">
                <a-form-model-item :label="$t('安卓版')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div style="color:orange;margin-bottom:10px">{{ $t('如需定制APP名称和图标，请将图标和名称发送给系统供应商，否则将使用默认图标和名称。') }}
                  </div>
                  <a-row>
                    <a-col :span="24" style="text-align: center;">
                      <div id="adQrcode" ref="adQrcode" style="width:160px;height:160px;margin: 10px auto;">
                        <img style="width:160px;height:160px;margin:auto" />
                      </div>
                    </a-col>
                    <a-col :span="24" style="text-align: center;">
                      <a id="downloadImgAd" @click="downloadImgAd" style="color: #008dd9">{{ $t('下载') }}</a>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="info.sysType == 6">
              <a-col :span="12">
                <a-form-model-item :label="$t('苹果版')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div style="color:orange;margin-bottom:10px">{{ $t('APP名称和图标可自定义，不设置则使用默认图标和名称。') }}</div>
                  <a-row>
                    <a-col :span="18">
                      <a-row>
                        <j-form-container>
                          <a-form-model ref="app" :model="deviceApp" :rules="validatorApp" slot="detail">
                            <a-row>
                              <a-col :span="12">
                                <a-form-model-item :label="$t('APP名称')" :labelCol="labelCol2" :wrapperCol="wrapperCol2"
                                  prop="name">
                                  <a-input v-model="deviceApp.name" :placeholder="$t('请输入APP名称')"></a-input>
                                </a-form-model-item>
                              </a-col>
                            </a-row>
                            <a-row>
                              <a-col :span="12">
                                <a-form-model-item :label="$t('APP图标')" :labelCol="labelCol2" :wrapperCol="wrapperCol2"
                                  prop="icon">
                                  <j-upload v-model="deviceApp.icon" fileType="image" :text="$t('选择')" :count="1"
                                    :multiple="false"></j-upload>
                                </a-form-model-item>
                              </a-col>
                            </a-row>
                            <a-row>
                              <a-col :span="12">
                                <a-row>
                                  <a-col :span="16" :offset="6">
                                    <a-button type="primary" :disabled="confirmLoading" @click="saveDeviceApp">{{
                                      $t('保存')
                                      }}</a-button>
                                  </a-col>
                                </a-row>
                              </a-col>
                            </a-row>
                          </a-form-model>
                        </j-form-container>
                      </a-row>
                    </a-col>
                    <a-col :span="6">
                      <a-row>
                        <a-col :span="24" style="text-align: center;">
                          <div v-if="iosUrl !== ''">
                            <div id="iosQrcode" ref="iosQrcode" style="width:160px;height:160px;margin: 10px auto;">
                              <img style="width:160px;height:160px;margin:auto" />
                            </div>
                          </div>
                          <div v-else style="color: red; margin-top: 10px;">
                            {{ $t('请联系系统供应商获取下载二维码') }}
                          </div>
                        </a-col>
                        <a-col :span="24" style="text-align: center;">
                          <a id="downloadImgIOS" @click="downloadImgIOS" style="color: #008dd9" v-if="iosUrl != ''">{{
                            $t('下载') }}</a>
                        </a-col>
                      </a-row>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
        </a-form-model>
      </j-form-container>
    </a-spin>
    <yarn-cert-modal ref="yarnModal" @ok="conSubmit" @close="getInfo"></yarn-cert-modal>
    <yarn-cert-modal ref="yarnQrModal" @ok="conQrPath" @close="getQrPath"></yarn-cert-modal>
  </a-card>
</template>
<script>
import axios from 'axios'
import Vue from 'vue'
import QRCode from 'qrcodejs2'
import { getAction, putAction, httpAction } from '@/api/manage'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import YarnCertModal from '@/views/setting/modules/YarnCertModal'

export default {
  name: 'AppletSetting',
  mixins: [],
  components: { YarnCertModal },
  data() {
    return {
      confirmLoading: false,
      model: {
        idKey: '',
        appletAppId: '',
        secretKey: '',
        appletAppSecret: '',
      },
      deviceApp: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      labelCol1: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol1: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      validatorRules: {
        appletAppId: [{ required: true, message: this.$t('请输入小程序AppID') }],
        appletAppSecret: [{ required: true, message: this.$t('请输入小程序AppSecret') }],
      },
      validatorApp: {
        name: [{ required: true, message: this.$t('请输入APP名称') }],
        icon: [{ required: true, message: this.$t('请选择APP图标') }],
      },
      url: {
        list: '/bis/bisSysParameter/queryByName',
        importExcelUrl: 'sys/common/uploadRes',
      },
      info: {},
      iosUrl: '',
      bizPath: ''
    }
  },
  created() {
    this.getInfo()
    this.getQrPath()
    this.getDeviceApp()
  },
  computed: {
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {
    getAction('/shop/bisShop/list', {}).then(async (res) => {
      if (res.success) {
        this.info = res.result.records[0]
        await this.getSysTem(this.info.type)
        if(this.info.sysType == 6){
          this.createQrcode()
          this.createIosQrcode()
        }
      } else {
        this.$message.warning(res.message)
      }
    })
    
  },
  methods: {
    getQrPath(){
      axios.all([this.fun3()]).then(
        axios.spread((r1) => {
          if (r1.success) {
            this.$set(this.model, 'pathKey', r1.result.id)
            this.$set(this.model, 'appletQrPath', r1.result.svalue)
            this.$set(this, 'bizPath', r1.result.svalue)
          }
        })
      )
    },
    saveQrPath(){
      let that = this
      // 触发表单验证
      that.$refs.form.validate((valid) => {
        if (valid) {
          if (that.model.pathKey) {
            that.$refs.yarnQrModal.edit()
            return
          }
          that.conQrPath()
        }
      })
    },
    conQrPath(){
      let that = this
      that.confirmLoading = true
      let httpurl = '/bis/bisSysParameter/saveBatch'
      let method = 'post'
      let query = []
      query.push({
        id: that.model.pathKey ? that.model.pathKey : '',
        name: 'appletQrPath',
        svalue: that.model.appletQrPath,
        comment: '小程序-扫普通二维码进',
      })
      httpAction(httpurl, query, method)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.getQrPath()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    /* 导入 */
    upload(info) {
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName },
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
          } else {
            this.$message.success(`${info.file.name + this.$t('文件上传成功')}`)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${this.$t('文件上传失败') + ': ' + info.file.msg} `)
      }
    },
    getInfo() {
      axios.all([this.fun1(), this.fun2()]).then(
        axios.spread((r1, r2) => {
          if (r1.success) {
            this.model.idKey = r1.result.id
            this.model.appletAppId = r1.result.svalue
          }
          if (r2.success) {
            this.model.secretKey = r2.result.id
            this.model.appletAppSecret = r2.result.svalue
          }
        })
      )
    },
    getDeviceApp() {
      getAction('/device/bisDeviceApp/list', {}).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.deviceApp = res.result.records[0]
          }
        }
      })
    },
    saveDeviceApp() {
      this.$refs.app.validate((valid) => {
        if (valid) {
          putAction('/device/bisDeviceApp/edit', {
            id: this.deviceApp.id,
            tenantId: this.deviceApp.tenantId,
            name: this.deviceApp.name,
            icon: this.deviceApp.icon,
          }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    fun1() {
      return getAction('/bis/bisSysParameter/queryByName', { name: 'appletAppId' })
    },
    fun2() {
      return getAction('/bis/bisSysParameter/queryByName', { name: 'appletAppSecret' })
    },
    fun3() {
      return getAction('/bis/bisSysParameter/queryByName', { name: 'appletQrPath' })
    },
    submitForm() {
      let that = this
      // 触发表单验证
      that.$refs.form.validate((valid) => {
        if (valid) {
          if (that.model.idKey || that.model.secretKey) {
            that.$refs.yarnModal.edit()
            return
          }
          that.conSubmit()
        }
      })
    },
    conSubmit() {
      let that = this
      that.confirmLoading = true
      let httpurl = '/bis/bisSysParameter/saveBatch'
      let method = 'post'
      let query = []
      query.push({
        id: that.model.idKey ? that.model.idKey : '',
        name: 'appletAppId',
        svalue: that.model.appletAppId,
        comment: '微信AppID',
      })
      query.push({
        id: that.model.secretKey ? that.model.secretKey : '',
        name: 'appletAppSecret',
        svalue: that.model.appletAppSecret,
        comment: '微信AppSecret',
      })
      httpAction(httpurl, query, method)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.getInfo()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    getSysTem(id){
      return new Promise(resolve => {
        getAction('/guest/sysType/queryById', { id: id }).then(res => {
          if(res.success){
            this.$set(this.info, 'sysType', res.result.code)
          }
          resolve()
        })
      })
    },
    createQrcode() {
      let name = '会员中心' + window.location.host.split('.')[0]
      let str = 'http://up.leyudm.com/AppUpdate/DownFile?appname=' + encodeURIComponent(name) + '&filename=' + encodeURIComponent(name) + ' V1.0.5.apk'
      document.getElementById('adQrcode').innerHTML = '' //获取生成二维码后显示的容器的ID
      this.adQrcode = new QRCode('adQrcode', {
        width: 160,
        height: 160,
        text: str,
        colorDark: '#000',
        colorLight: '#fff',
        title: '',
      })
      this.adQrcode._el.title = ''
    },
    downloadImgAd() {
      let that = this
      var img = document.getElementById('adQrcode').getElementsByTagName('img')[0]
      var canvas = document.createElement('canvas')
      canvas.width = 360
      canvas.height = 360
      var ctx = canvas.getContext('2d')
      ctx.beginPath()
      ctx.font = 'normal 18px Arial'
      ctx.fillStyle = '#000'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(that.info.name, 180, 40)
      ctx.drawImage(img, 100, 60)
      ctx.font = 'normal 14px Arial'
      ctx.textAlign = 'left'
      ctx.fillText(that.$t('1、打开手机浏览器'), 100, 240)
      ctx.fillText(that.$t('2、选择扫一扫'), 100, 260)
      ctx.fillText(that.$t('3、扫描上图二维码'), 100, 280)
      ctx.textAlign = 'center'
      ctx.fillStyle = '#F00'
      ctx.fillText(that.$t('安卓版'), 180, 300)
      var url = canvas.toDataURL('image/png')
      document.getElementById('downloadImgAd').setAttribute('href', url)
      document.getElementById('downloadImgAd').setAttribute('download', that.$t('会员中心APP') + '--' + that.info.name + '.jpg')
    },
    createIosQrcode() {
      getAction('/device/bisDeviceApp/getIosUrl', {}).then((res) => {
        if(res.success) {
          if(res.result != null) {
            this.iosUrl = res.result 
            this.$nextTick(()=>{
              document.getElementById('iosQrcode').innerHTML = '' //获取生成二维码后显示的容器的ID
              this.iosQrcode = new QRCode('iosQrcode', {
                width: 160,
                height: 160,
                text: this.iosUrl,
                colorDark: '#000',
                colorLight: '#fff',
                title: '',
              })
              this.iosQrcode._el.title = ''
            })
          } else {
            return;
          }
        }
      })
    },
    downloadImgIOS(){
      let that = this
      var img = document.getElementById('iosQrcode').getElementsByTagName('img')[0]
      var canvas = document.createElement('canvas')
      canvas.width = 360
      canvas.height = 360
      var ctx = canvas.getContext('2d')
      ctx.beginPath()
      ctx.font = 'normal 18px Arial'
      ctx.fillStyle = '#000'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(that.info.name, 180, 40)
      ctx.drawImage(img, 100, 60)
      ctx.font = 'normal 14px Arial'
      ctx.textAlign = 'left'
      ctx.fillText(that.$t('1、打开手机浏览器'), 100, 240)
      ctx.fillText(that.$t('2、选择扫一扫'), 100, 260)
      ctx.fillText(that.$t('3、扫描上图二维码'), 100, 280)
      ctx.textAlign = 'center'
      ctx.fillStyle = '#F00'
      ctx.fillText(that.$t('苹果版'), 180, 300)
      var url = canvas.toDataURL('image/png')
      document.getElementById('downloadImgIOS').setAttribute('href', url)
      document.getElementById('downloadImgIOS').setAttribute('download', that.$t('会员中心APP') + '--' + that.info.name + '.jpg')
    }
  },
}
</script>